package cloudPayAdmin.admin.controller.traffic;

import cloudPayAdmin.admin.dbapp.entity.traffic.TTrafficDetector;
import cloudPayAdmin.admin.service.traffic.TrafficDetectorService;
import cloudPayAdmin.constant.BusiError;
import cloudPayAdmin.constant.Constant;
import cloudPayAdmin.util.*;
import cloudPayAdmin.util.pagebean.HqlPageBeanHelper;
import cloudPayAdmin.util.pagebean.HqlParam;
import cloudPayAdmin.util.pagebean.PageBean;
import com.alibaba.fastjson.JSON;
import com.project.m.api.common.biz.resp.BizResp;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Controller
@RequestMapping("/traffic/detector")
public class TrafficDetectorController {
    @Autowired
    HqlPageBeanHelper hqlPageBeanHelper;

    @PersistenceContext(unitName = "entityManagerFactory")
    EntityManager entityManager;

    @Autowired
    Environment env;

    @Autowired
    TrafficDetectorService trafficDetectorService;

    @RequestMapping(value = "/toListPage")
    public String toListPage(HttpServletRequest request, Map<String, Object> model) {
        //request.setAttribute("typeMap", TPicture.initTypeMap());
        return "/traffic/detector/detector-list";
    }

    @RequestMapping("/getDetectorListData")
    @ResponseBody
    public String getDetectorListData(HttpServletRequest request) {
        Map<String, Object> paramMap = WebUtil.getSearchParam(request);
        paramMap = WebUtil.formatDateRange(paramMap, TimeUtil.DATE_PATTERN_NOSEPARTOR);
        // 需要映射的实体类
        HqlParam hqlParam = WebUtil.buildHqlParam(paramMap, TTrafficDetector.class, request);
        PageBean<TTrafficDetector> cloudpayCardPage = hqlPageBeanHelper.findHqlPageBean(entityManager, hqlParam);

        for(TTrafficDetector trafficDetector : cloudpayCardPage.getContent()) {
            if(StringUtils.isNotBlank(trafficDetector.getScreenShot())) {
                trafficDetector.setScreenShot(AliyunUtil.getPublicUrl(AliyunUtil.PUBLIC_BUCKETNAME, trafficDetector.getScreenShot(), Boolean.FALSE));
            }
        }
        AdminLteDataTableResp<TTrafficDetector> resp = AdminLteUtil.pageBeanToAdminLteDataTableResp(cloudpayCardPage,request);
        return resp.toAdminLteJsonString(TTrafficDetector.class);
    }

    @RequestMapping("/toDetectorEditPage")
    public String toDetectorEditPage(HttpServletRequest request, Long trafficDetectorId) {
        TTrafficDetector trafficDetector = null;
        if (trafficDetectorId != null) {
            trafficDetector = trafficDetectorService.findById(trafficDetectorId);
        }
        if (trafficDetector == null) {
            trafficDetector = new TTrafficDetector();
        }
        trafficDetector.setScreenShot(AliyunUtil.getPublicUrl(AliyunUtil.PUBLIC_BUCKETNAME, trafficDetector.getScreenShot(), Boolean.FALSE));
        //picture.setUrl(AliyunUtil.getPublicUrl(AliyunUtil.PUBLIC_BUCKETNAME, picture.getUrl(), Boolean.FALSE));

        request.setAttribute("trafficDetector", trafficDetector);
        //request.setAttribute("typeMap", TPicture.initTypeMap());

        return "traffic/detector/detector-edit";
    }

    @RequestMapping("/editDetector")
    public String editDetector(HttpServletRequest request, TTrafficDetector trafficDetector, MultipartFile screenShotInput) throws Exception {

        if (trafficDetector.getTrafficDetectorId() == null) {   //新增
            if (screenShotInput != null && StringUtils.isNotBlank(screenShotInput.getOriginalFilename())) {
                String key = AliyunUtil.generateAliyunKey(Constant.PICTURE_FILE_PATH, screenShotInput.getOriginalFilename());
                AliyunUtil.uploadFile(AliyunUtil.PUBLIC_BUCKETNAME, screenShotInput.getInputStream(), key);
                trafficDetector.setScreenShot(key);
            }

            //取坐标
            if (!StringUtils.isEmpty(trafficDetector.getAddress())) {
                //{"status":0,"result":{"location":{"lng":113.29698670392162,"lat":23.127555443333077},"precise":0,"confidence":60,"level":"道路"}}
                Map locationMap = BMapUtil.getLocationByAddress(trafficDetector.getAddress());
                if (MapUtils.getInteger(locationMap, "status") == 0) {
                    //经度
                    Float longitude = MapUtils.getFloat(MapUtils.getMap(MapUtils.getMap(locationMap, "result"), "location"), "lng");
                    //纬度
                    Float latitude = MapUtils.getFloat(MapUtils.getMap(MapUtils.getMap(locationMap, "result"), "location"), "lat");
                    trafficDetector.setLongitude(String.valueOf(longitude));
                    trafficDetector.setLatitude(String.valueOf(latitude));
                }
            }

            //生成设备号
            if (StringUtils.isEmpty(trafficDetector.getCode())) {
                trafficDetector.setCode(IdGenerator.generateMerchantId(IdGenerator.ORDERID_PREFIX_DETECTOR, "00", "0000"));
            }

            trafficDetector.setStatus(TTrafficDetector.STATUS_IN_USE);
            trafficDetector.setCreateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
            trafficDetector.setUpdateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
            trafficDetectorService.save(trafficDetector);
        } else {    //更新
            TTrafficDetector originalTrafficDetector = trafficDetectorService.findById(trafficDetector.getTrafficDetectorId());

            if (screenShotInput != null && StringUtils.isNotBlank(screenShotInput.getOriginalFilename())) {
                String key = AliyunUtil.generateAliyunKey(Constant.PICTURE_FILE_PATH, screenShotInput.getOriginalFilename());
                AliyunUtil.uploadFile(AliyunUtil.PUBLIC_BUCKETNAME, screenShotInput.getInputStream(), key);
                originalTrafficDetector.setScreenShot(key);
            }

            if (StringUtils.isNotBlank(trafficDetector.getAddress()) && !StringUtils.equals(originalTrafficDetector.getAddress(), trafficDetector.getAddress())) {
                Map locationMap = BMapUtil.getLocationByAddress(trafficDetector.getAddress());
                if (MapUtils.getInteger(locationMap, "status") == 0) {
                    //经度
                    Float longitude = MapUtils.getFloat(MapUtils.getMap(MapUtils.getMap(locationMap, "result"), "location"), "lng");
                    //纬度
                    Float latitude = MapUtils.getFloat(MapUtils.getMap(MapUtils.getMap(locationMap, "result"), "location"), "lat");
                    originalTrafficDetector.setLongitude(String.valueOf(longitude));
                    originalTrafficDetector.setLatitude(String.valueOf(latitude));
                    originalTrafficDetector.setAddress(trafficDetector.getAddress());
                } else {
                    originalTrafficDetector.setLongitude("");
                    originalTrafficDetector.setLatitude("");
                    originalTrafficDetector.setAddress(trafficDetector.getAddress());
                }
            } else {
                originalTrafficDetector.setLongitude("");
                originalTrafficDetector.setLatitude("");
                originalTrafficDetector.setAddress(trafficDetector.getAddress());
            }
            //生成设备号
            if (StringUtils.isEmpty(originalTrafficDetector.getCode())) {
                originalTrafficDetector.setCode(IdGenerator.generateMerchantId(IdGenerator.ORDERID_PREFIX_DETECTOR, "00", "0000"));
            }
            originalTrafficDetector.setName(trafficDetector.getName());
            originalTrafficDetector.setDescription(trafficDetector.getDescription());
            originalTrafficDetector.setVerifyCode(trafficDetector.getVerifyCode());
            originalTrafficDetector.setDeviceSerial(trafficDetector.getDeviceSerial());
            originalTrafficDetector.setVideoRtmpUrlSmooth(trafficDetector.getVideoRtmpUrlSmooth());
            originalTrafficDetector.setVideoRtmpUrlHd(trafficDetector.getVideoRtmpUrlHd());
            originalTrafficDetector.setVideoUrlSmooth(trafficDetector.getVideoUrlSmooth());
            originalTrafficDetector.setVideoUrlHd(trafficDetector.getVideoUrlHd());
            originalTrafficDetector.setUpdateTime(TimeUtil.getCurrTime(TimeUtil.DATE_PATTERN_NOSEPARTOR));
            trafficDetectorService.save(originalTrafficDetector);
        }
        return "redirect:/traffic/detector/toListPage";
    }

    /**
     * 删除摄像头
     */
    @RequestMapping("/deleteDetector")
    @ResponseBody
    public String deleteDetector(HttpServletRequest request,Long trafficDetectorId) {
        //System.out.println("deleteDetector trafficDetectorId = " + trafficDetectorId);
        BizResp resp = new BizResp();
        trafficDetectorService.deleteById(trafficDetectorId);
        resp.setResult_code(BusiError.ERR_CODE_SUCCESS);
        return JSON.toJSONString(resp);
    }
}
